"""
pytest配置文件

为测试提供共享的fixture和配置。
"""

import pytest
import tempfile
import os
from unittest.mock import Mock, MagicMock


@pytest.fixture
def temp_backup_file():
    """
    创建临时备份文件的fixture
    
    示例值：
    - 返回：临时文件路径
    - 使用：用于测试备份文件处理
    """
    with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.sql') as f:
        f.write("CREATE TABLE users (id INT, name VARCHAR(100));")
        temp_file = f.name
    
    yield temp_file
    
    # 清理临时文件
    if os.path.exists(temp_file):
        os.unlink(temp_file)


@pytest.fixture
def temp_config_file():
    """
    创建临时配置文件的fixture
    
    示例值：
    - 返回：临时配置文件路径
    - 使用：用于测试配置加载
    """
    config_content = """
[database]
host = localhost
port = 3306
user = test_user
password = test_password
database = test_db

[backup]
output_dir = /tmp/backups
compress = true

[git]
repo_url = https://github.com/test/backup.git
local_path = /tmp/backup_repo
"""
    
    with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.ini') as f:
        f.write(config_content)
        temp_file = f.name
    
    yield temp_file
    
    # 清理临时文件
    if os.path.exists(temp_file):
        os.unlink(temp_file)


@pytest.fixture
def mock_mysql_backup():
    """
    模拟MySQLBackup对象的fixture
    
    示例值：
    - 返回：模拟的MySQLBackup对象
    - 使用：用于测试MySQL备份功能
    """
    mock_backup = MagicMock()
    mock_backup.connect.return_value = True
    mock_backup.disconnect.return_value = True
    mock_backup.get_tables.return_value = ['users', 'products', 'orders']
    mock_backup.backup_table.return_value = "backup_users.sql"
    mock_backup.backup_database.return_value = ["backup_users.sql", "backup_products.sql", "backup_orders.sql"]
    
    return mock_backup


@pytest.fixture
def mock_postgresql_backup():
    """
    模拟PostgreSQLBackup对象的fixture
    
    示例值：
    - 返回：模拟的PostgreSQLBackup对象
    - 使用：用于测试PostgreSQL备份功能
    """
    mock_backup = MagicMock()
    mock_backup.connect.return_value = True
    mock_backup.disconnect.return_value = True
    mock_backup.get_tables.return_value = ['users', 'products', 'orders']
    mock_backup.backup_table.return_value = "backup_users.sql"
    mock_backup.backup_database.return_value = ["backup_users.sql", "backup_products.sql", "backup_orders.sql"]
    
    return mock_backup


@pytest.fixture
def mock_mariadb_backup():
    """
    模拟MariaDBBackup对象的fixture
    
    示例值：
    - 返回：模拟的MariaDBBackup对象
    - 使用：用于测试MariaDB备份功能
    """
    mock_backup = MagicMock()
    mock_backup.connect.return_value = True
    mock_backup.disconnect.return_value = True
    mock_backup.get_tables.return_value = ['users', 'products', 'orders']
    mock_backup.backup_table.return_value = "backup_users.sql"
    mock_backup.backup_database.return_value = ["backup_users.sql", "backup_products.sql", "backup_orders.sql"]
    
    return mock_backup


@pytest.fixture
def mock_diff_checker():
    """
    模拟DiffChecker对象的fixture
    
    示例值：
    - 返回：模拟的DiffChecker对象
    - 使用：用于测试差异检查功能
    """
    mock_checker = MagicMock()
    mock_checker.compare_files.return_value = False
    mock_checker.compare_directories.return_value = False
    mock_checker.get_file_differences.return_value = [
        {"line": 1, "old": "CREATE TABLE users (id INT)", "new": "CREATE TABLE users (id INT, name VARCHAR(100))"}
    ]
    mock_checker.get_directory_differences.return_value = [
        {"file": "users.sql", "status": "modified"}
    ]
    
    return mock_checker


@pytest.fixture
def mock_git_handler():
    """
    模拟GitHandler对象的fixture
    
    示例值：
    - 返回：模拟的GitHandler对象
    - 使用：用于测试Git上传功能
    """
    from database_backup.git import GitHandler
    mock_handler = MagicMock(spec=GitHandler)
    mock_handler.clone_repository.return_value = True
    mock_handler.initialize_repository.return_value = True
    mock_handler.add_files.return_value = True
    mock_handler.commit_changes.return_value = True
    mock_handler.push_changes.return_value = True
    mock_handler.upload_backup_files.return_value = True
    
    return mock_handler


@pytest.fixture
def cli_runner():
    """
    CLI运行器的fixture
    
    示例值：
    - 返回：Click测试运行器
    - 使用：用于测试命令行接口
    """
    from click.testing import CliRunner
    return CliRunner()


@pytest.fixture
def sample_backup_config():
    """
    示例备份配置的fixture
    
    示例值：
    - 返回：备份配置字典
    - 使用：用于测试配置处理
    """
    return {
        "database": {
            "type": "mysql",
            "host": "localhost",
            "port": 3306,
            "user": "test_user",
            "password": "test_password",
            "database": "test_db"
        },
        "backup": {
            "output_dir": "/tmp/backups",
            "compress": True,
            "include_tables": ["users", "products"],
            "exclude_tables": ["logs"]
        },
        "git": {
            "repo_url": "https://github.com/test/backup.git",
            "local_path": "/tmp/backup_repo",
            "branch": "main"
        }
    }


@pytest.fixture
def temp_backup_directory():
    """
    创建临时备份目录的fixture
    
    示例值：
    - 返回：临时目录路径
    - 使用：用于测试目录操作
    """
    temp_dir = tempfile.mkdtemp()
    
    # 创建一些示例备份文件
    backup_files = ["backup_users.sql", "backup_products.sql", "backup_orders.sql"]
    for file_name in backup_files:
        file_path = os.path.join(temp_dir, file_name)
        with open(file_path, 'w') as f:
            f.write(f"-- Backup for {file_name.replace('backup_', '').replace('.sql', '')}\n")
    
    yield temp_dir
    
    # 清理临时目录
    import shutil
    if os.path.exists(temp_dir):
        shutil.rmtree(temp_dir)


@pytest.fixture
def sample_database_connection_params():
    """
    示例数据库连接参数的fixture
    
    示例值：
    - 返回：连接参数字典
    - 使用：用于测试数据库连接
    """
    return {
        "mysql": {
            "host": "localhost",
            "port": 3306,
            "user": "mysql_user",
            "password": "mysql_pass",
            "database": "mysql_db"
        },
        "postgresql": {
            "host": "localhost",
            "port": 5432,
            "user": "postgres_user",
            "password": "postgres_pass",
            "database": "postgres_db"
        },
        "mariadb": {
            "host": "localhost",
            "port": 3306,
            "user": "mariadb_user",
            "password": "mariadb_pass",
            "database": "mariadb_db"
        }
    }


def pytest_configure(config):
    """
    pytest配置钩子
    
    示例值：
    - 参数：pytest配置对象
    - 使用：配置测试环境
    """
    # 添加自定义标记
    config.addinivalue_line(
        "markers", "slow: 标记为慢速测试"
    )
    config.addinivalue_line(
        "markers", "integration: 标记为集成测试"
    )
    config.addinivalue_line(
        "markers", "unit: 标记为单元测试"
    )


def pytest_collection_modifyitems(config, items):
    """
    修改测试项集合的钩子
    
    示例值：
    - 参数：config - pytest配置对象
    - 参数：items - 测试项列表
    - 使用：修改测试执行顺序或跳过某些测试
    """
    # 可以在这里添加自定义逻辑，比如跳过某些测试
    pass